import {uSelectMyAllDevSetAndStatus} from "./../../api/setting"
import {getStorage, setStorage} from "@/utils/localstoreage"
import Taro from "@tarojs/taro"
import {observable, computed, action} from "mobx"
import {createContext} from "react"

class Setting {
	/**设置页状态 */
	@observable devListShowType: SettingStore.DevListShowType = null
	/**
	 * 设置页设备列表展现模式
	 * @desc 从本地缓存取值，没有值时默认为 single。有值时返回并更新home.devListShowType
	 */
	@computed get getDevListShowType(): SettingStore.DevListShowType {
		if (this.devListShowType === null) {
			let typeOflocal = getStorage(
				"settingDevListShowType"
			) as SettingStore.DevListShowType | null
			if (!typeOflocal) {
				this.changeDevListShowType("config", false)
				return "config"
			}
			if (typeOflocal !== this.devListShowType) {
				this.changeDevListShowType(typeOflocal, false)
			}
			return typeOflocal
		} else {
			return this.devListShowType
		}
	}

	/**修改设置页设备列表展现模式 */
	@action.bound
	changeDevListShowType(val: SettingStore.DevListShowType, showModal?: boolean) {
		setStorage("settingDevListShowType", val)
		this.devListShowType = val
		if (showModal || showModal === undefined) {
			Taro.showModal({
				title: "设备卡片变更成功",
				showCancel: false,
				confirmText: "好的",
				cancelColor: "#576b95"
			})
		}
	}
	@observable detilPack: SettingStore.DetailPack = {
		standRangeRatio: 0,
		devRunStatus: "",
		devCount: 0,
		totalCheckHour: 0,
		devExceptionCount: 0
	}
	@observable devList: SettingStore.DevList | null = null

	/**获取设置页面卡片数据 */
	@action.bound
	updateDevList() {
		console.log(Taro.getStorageSync("isShowLoading") == "")

		// if (
		// 	Taro.getStorageSync("isShowLoading") == null ||
		// 	Taro.getStorageSync("isShowLoading") == undefined ||
		// 	Taro.getStorageSync("isShowLoading") == ""
		// ) {
		Taro.showLoading({
			title: "加载中"
		})
		// 	Taro.setStorageSync("isShowLoading", "false")
		// 	// 	localStorage.setItem("isShowLoading", "false")
		// }

		// setIsOneLoading(true)
		// console.log(isOneLoading)

		let userId = getStorage("userId")
		if (!userId) return
		uSelectMyAllDevSetAndStatus({userId})
			.then(res => {
				console.log("uSelectMyAllDevSetAndStatus", res)

				this.devList = res.data.myDevSetPackList || []
				let defaultDetailPack = {
					standRangeRatio: 0,
					devRunStatus: "",
					devCount: 0,
					totalCheckHour: 0,
					devExceptionCount: 0
				}
				for (const key in this.detilPack) {
					const val = res.data[key]
					defaultDetailPack[key] = val
				}
				this.detilPack = defaultDetailPack
				Taro.hideLoading()
			})
			.catch(() => {
				this.devList = []
			})
	}
}

const settingStore = createContext(new Setting())
export default settingStore
